﻿<%@ WebHandler Language="C#" Class="Handler" %>

using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;

public class Handler : IHttpHandler
{
    public static string Copyright
    {
        get
        {
            string copyright = System.Configuration.ConfigurationManager.AppSettings["copyright"];
            return copyright;
        }
    }
    
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain"; //"application/json";
        var r = new List<ViewDataUploadFilesResult>();
        var js = new JavaScriptSerializer();

        var dir = context.Request["dir"];
        foreach (string file in context.Request.Files)
        {
            HttpPostedFile hpf = context.Request.Files[file];
            if (hpf != null)
            {
                string fileName;
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new[] { '\\' });
                    fileName = files[files.Length - 1];
                }
                else
                {
                    fileName = hpf.FileName;
                }
                if (hpf.ContentLength == 0)
                    continue;

                var savedFileName = MakeCopyright(dir, hpf);
                //string savedFileName = "c:\\tmp\\" + fileName;
                //hpf.SaveAs(savedFileName);

                r.Add(new ViewDataUploadFilesResult
                {
                    Thumbnail_url = savedFileName,
                    Name = fileName,
                    Length = hpf.ContentLength,
                    Type = hpf.ContentType
                });
                var uploadedFiles = new
                {
                    files = r.ToArray()
                };
                string jsonObj = js.Serialize(uploadedFiles);
                
                // IE8 need plain-text
                {
                    //jsonObj.ContentEncoding = System.Text.Encoding.UTF8;
                    //jsonObj.ContentType = "application/json;";
                }
                context.Response.Write(jsonObj);
            }
        }
    }
    private string MakeCopyright(string dir, HttpPostedFile fileUpload)
    {
        int index = fileUpload.FileName.LastIndexOf('.');
        string fileName = System.DateTime.Now.ToString("yyyyMMdd_HHmmss") + fileUpload.FileName.Substring(index);

        string originalPath = HttpContext.Current.Server.MapPath("~" + Define.ImageFolder + dir + '/') + fileName;
        string thumbPath = HttpContext.Current.Server.MapPath("~" + Define.ImageFolder + dir + "/thumb/") + fileName;
        string copyrightPath = HttpContext.Current.Server.MapPath("~" + Define.ImageFolder + dir + "/copyright/") + fileName;
        string tempName = Path.GetTempFileName();
        fileUpload.SaveAs(originalPath);

        // Save thumb
        var imgResizer = new phudieuhungthinh.Helpers.ImageResizer
        {
            OutputFormat = phudieuhungthinh.Helpers.ImageFormat.Jpeg,
            MaxWidth = 200,
            MaxHeight = 160
        };
        var directoryInfo = new FileInfo(thumbPath).Directory;
        if (directoryInfo != null && directoryInfo.Exists)
        {
            imgResizer.Resize(fileUpload, thumbPath);
        }

        directoryInfo = new FileInfo(copyrightPath).Directory;
        if (directoryInfo != null && directoryInfo.Exists)
        {
            imgResizer.OutputFormat = phudieuhungthinh.Helpers.ImageFormat.Jpeg;
            imgResizer.MaxWidth = 1020;
            imgResizer.MaxHeight = 900;
            imgResizer.Resize(originalPath, tempName);

            // Draw copy right
            var imgHelper = new phudieuhungthinh.Helpers.ImageHelper();
            imgHelper.WriteCopyright(Copyright, string.Empty, tempName, copyrightPath);
        }

        return fileName;
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

public class ViewDataUploadFilesResult
{
    public string Thumbnail_url { get; set; }
    public string Name { get; set; }
    public int Length { get; set; }
    public string Type { get; set; }
}